package cn.lanjh.oss;

import io.minio.MinioClient;
import io.minio.errors.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmlpull.v1.XmlPullParserException;

import javax.activation.MimetypesFileTypeMap;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/***
 * minIO 文件存储
 * @author lanjh
 *
 */
public class MinioCloudStorageService extends CloudStorageService {
    
	final static Logger logger = LoggerFactory.getLogger(MinioCloudStorageService.class);
	
	private MinioClient minioClient;
	 public MinioCloudStorageService(CloudStorageConfig config) {
	        this.config = config;
	        //初始化
	        init();
	    }
	 
	 private void init() {
		// minioClient=new MinioClient("http://10.142.12.94:9000", MINIO_ACCESS_KEY,MINIO_SECRET_KEY);
		 try {
			minioClient=new MinioClient(config.getMinioDomain(),config.getMinioAccessKey(),config.getMinioSecretKey());
		    if(minioClient.bucketExists(config.getMinioBucketName())) {
		    	//System.out.println("已存在"+config.getMinioBucketName());
		    	logger.warn("已存在【{}】桶",config.getMinioBucketName());
		    }else {
		    	minioClient.makeBucket(config.getMinioBucketName());
		    	//System.out.println("成功创建"+config.getMinioBucketName());
		    	logger.info("成功创建【{}】桶",config.getMinioBucketName());
		    }
		 } catch (InvalidEndpointException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidPortException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidBucketNameException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InsufficientDataException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoResponseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ErrorResponseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InternalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RegionConflictException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	 }
	
	@Override
	public String upload(byte[] data, String path) {
		// TODO Auto-generated method stub
		 return this.upload(new ByteArrayInputStream(data), path);
	}

	@Override
	public String uploadSuffix(byte[] data, String suffix) {
		// TODO Auto-generated method stub
		 return this.upload(new ByteArrayInputStream(data), this.getPath(config.getMinioPrefix(), suffix));
	}

	@Override
	public String upload(InputStream inputStream, String path) {
		// TODO Auto-generated method stub
		  try {
				minioClient.putObject(config.getMinioBucketName(), path, inputStream, getContentType(path));
				logger.info("文件上传成功,桶:{}  路径：{}",config.getMinioBucketName(),path);
			} catch (InvalidKeyException | InvalidBucketNameException | NoSuchAlgorithmException | InsufficientDataException
					| NoResponseException | ErrorResponseException | InternalException | InvalidArgumentException
					| IOException | XmlPullParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.error("文件上传失败,桶:{}  路径：{}",config.getMinioBucketName(),path);
			}
		  
		  return config.getMinioProxyServer() + "/" + config.getMinioBucketName() + "/" + path;
		/*String url;
		try {
			url = minioClient.getObjectUrl(config.getMinioBucketName(), path);
			logger.info("文件访问路径  {}",url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("文件访问路径获取失败，原因：{}",e.getMessage());
			url= config.getMinioDomain() + "/" + config.getMinioBucketName() + "/" + path;
			logger.error("获取下载路径，path：{}",url);
		} 
		return url;*/
	}
	
	public String getContentType(String fileUrl) {
		String contentType = null;
        try {
        	contentType = new MimetypesFileTypeMap().getContentType(new File(fileUrl));
        } catch (Exception e) {
            e.printStackTrace();
        }
       // System.out.println("getContentType, File ContentType is : " + contentType);
        logger.info("getContentType,   File :{}  ContentType is : {}",fileUrl,contentType);
        return contentType;
        
	}

	@Override
	public String uploadSuffix(InputStream inputStream, String suffix) {
		// TODO Auto-generated method stub
		return upload(inputStream,this.getPath(config.getMinioPrefix(), suffix));
	}

}
